<template>
  <div>
    <app-head></app-head>
    <app-body>
      <div class="chat-container">
        <div class="chat-header">
          <div class="chat-header-info">
            <el-image
              style="width: 40px; height: 40px; border-radius: 50%;"
              :src="otherUser.avatarUrl"
              fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-user-solid"></i>
              </div>
            </el-image>
            <span class="nickname">{{otherUser.nickname}}</span>
          </div>
        </div>

        <div class="chat-messages" ref="messageContainer">
          <div v-for="(message, index) in messages" 
               :key="index" 
               :class="['message-item', isCurrentUser(message) ? 'message-right' : 'message-left']">
            <div class="message-avatar" v-if="!isCurrentUser(message)">
              <el-image
                style="width: 40px; height: 40px; border-radius: 50%;"
                :src="otherUser.avatarUrl"
                fit="cover">
                <div slot="error" class="image-slot">
                  <i class="el-icon-user-solid"></i>
                </div>
              </el-image>
            </div>
            <div class="message-content">
              <div class="message-text">{{message.content}}</div>
              <div class="message-time">{{formatTime(message.createdAt)}}</div>
            </div>
            <div class="message-avatar" v-if="isCurrentUser(message)">
              <el-image
                style="width: 40px; height: 40px; border-radius: 50%;"
                :src="currentUser.avatarUrl"
                fit="cover">
                <div slot="error" class="image-slot">
                  <i class="el-icon-user-solid"></i>
                </div>
              </el-image>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <el-input
            v-model="newMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入消息..."
            @keyup.enter.native="sendMessage"
          ></el-input>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
    </app-body>
  </div>
</template>

<script>
import AppHead from '../common/AppHeader.vue';
import AppBody from '../common/AppPageBody.vue';

export default {
  name: "chat",
  components: {
    AppHead,
    AppBody
  },
  data() {
    return {
      chatId: null,
      messages: [],
      newMessage: '',
      otherUser: {
        nickname: '',
        avatarUrl: ''
      },
      currentUser: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      refreshTimer: null
    };
  },
  created() {
    // 检查是否登录
    const token = localStorage.getItem('token');
    if (!token) {
      this.$message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 获取路由参数
    this.chatId = this.$route.query.chatId;
    const otherUserId = this.$route.query.sellerId === this.currentUser.userId ? 
      this.$route.query.buyerId : this.$route.query.sellerId;

    if (!this.chatId || !otherUserId) {
      this.$message.error('聊天参数错误');
      this.$router.push('/message');
      return;
    }

    // 加载对方用户信息
    this.loadOtherUserInfo(otherUserId);
    // 加载聊天记录
    this.loadChatHistory();
    
    // 设置定时刷新
    this.refreshTimer = setInterval(() => {
      this.loadChatHistory();
    }, 3000);
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  },
  methods: {
    loadOtherUserInfo(userId) {
      this.$api.getUserDetail(userId).then(res => {
        if (res.code === 200 && res.data) {
          this.otherUser = {
            nickname: res.data.nickname || res.data.userName || '未知用户',
            avatarUrl: res.data.avatarUrl || ''
          };
        }
      });
    },
    loadChatHistory() {
      this.$api.getChatHistory(this.chatId).then(res => {
        if (res.code === 200) {
          this.messages = res.data;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }
      });
    },
    sendMessage() {
      if (!this.newMessage.trim()) {
        return;
      }

      this.$api.sendMessage(this.chatId, {
        content: this.newMessage.trim()
      }).then(res => {
        if (res.code === 200) {
          this.newMessage = '';
          this.loadChatHistory();
        } else {
          this.$message.error(res.message || '发送失败');
        }
      }).catch(err => {
        console.error('发送消息失败:', err);
        this.$message.error('网络错误，请稍后重试');
      });
    },
    isCurrentUser(message) {
      return Number(message.senderId) === Number(this.currentUser.userId);
    },
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    },
    scrollToBottom() {
      const container = this.$refs.messageContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  background-color: #f5f5f5;
}

.chat-header {
  background-color: #fff;
  padding: 10px 20px;
  border-bottom: 1px solid #e6e6e6;
}

.chat-header-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.nickname {
  font-size: 16px;
  font-weight: 500;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message-left {
  justify-content: flex-start;
}

.message-right {
  justify-content: flex-end;
}

.message-avatar {
  margin: 0 10px;
}

.message-content {
  max-width: 60%;
}

.message-text {
  padding: 10px 15px;
  border-radius: 10px;
  word-break: break-word;
}

.message-left .message-text {
  background-color: #fff;
  border: 1px solid #e6e6e6;
}

.message-right .message-text {
  background-color: #409EFF;
  color: #fff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: center;
}

.chat-input {
  background-color: #fff;
  padding: 20px;
  border-top: 1px solid #e6e6e6;
  display: flex;
  gap: 10px;
}

.chat-input .el-textarea {
  flex: 1;
}

.chat-input .el-button {
  align-self: flex-end;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-slot i {
  font-size: 20px;
}
</style>